$(document).ready(function () {


    layui.use(function () {

        var layer = layui.layer;

        // 表格
        form = layui.form;
        form.on('select(type-select)', function (data) {
            $('div[lay-filter="search"]').click();
        });
        form.on('select(status-select)', function (data) {
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            var persons = []
            $('.bound-item').each(function (index) {
                if ($(this).find('.person-item').children().length != 0) {
                    persons.push({
                        "personId": $(this).find('.person-item').attr('id').split('-')[2],
                        "seqNo": index
                    })

                }
            });

            data.field.persons = persons

            new AjaxChain()
                .setUrl('/train/team/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer)
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });

        initSubMenu();
        queryTable();

        new ST().trainProject().then(data => {
            trainProject = data;
        })


    });
})
var params = {};//查询条件参数
var form, unit;
var drawer;//抽屉实例
var curId = null;//当前选中考核标准ID
var trainProject = ''

//查询考核标准类型列表
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/train/team/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'name', title: '项目名称', align: "center" },
                { field: 'persons', title: '组成员', align: "center" },
                {
                    title: '状态', align: "center",
                    templet: '#ID-table-templet-switch'
                },
                { field: 'createTime', title: '创建时间', align: "center" },
                {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                <div onclick='tableHandle(1,${res})' class="table-edit layui-btn">
                                  <img src="../static/img/edit.png">编辑
                                </div>
                                <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    }
                }
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

        layui.form.on('switch(templet-status)', function (obj) {

            var id = this.value;

            var name = this.name;
            new AjaxChain()
                .setUrl('/train/team/operate')
                .setData(JSON.stringify(
                    {
                        id: id,
                        type: obj.elem.checked ? 1 : 2
                    }
                ))
                .setMethod('post')
                .then(data => {
                    layer.msg('操作成功', { icon: 1, time: 1500 });
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openBound(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/train/team/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openBound(1)
            break;


        default:
            break;
    }
}



// 人员绑定组弹窗
openBound = (type, res) => {
    drawer = layer.open({
        type: 1,
        title: (type == 1 ? "新增" : "编辑") + '训练组',
        move: false,
        content: $('#ID-bound-templet').html(),
        area: ['80%', '90%'], // 初始宽高
        success: function (layero, index) {

            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }

            new ST().firemen(1).then(data => {

                $('#person-list .bound-con')
                    .empty()
                    .append(
                        data.reduce((x, y) => {
                            var res1 = JSON.stringify(y)
                            return x + `<div class="person-item" id="person-${y.id}" onclick='choosePerson(${res1},this)' data-id=${y.id}>
                                            <img src="${y.photoPath ? ('/images/' + y.photoPath) : '../static/img/photo.png'}">
                                            <span>${y.name}</span>
                                        </div>`
                        }, ''))

                if (type == 1) {
                    var str = ''

                    for (var i = 0; i < 12; i++) {
                        str = str + `<div class="bound-item">
                                        <div class="bound-item-seq">${i}</div>
                                        <i class="layui-icon layui-icon-disabled" title="临时禁用此位置" onclick=disabledPerson(this,${i})></i>
                                        <div class="person-item">
                                        </div>
                                    </div>`
                    }

                    $('#bound-list .bound-con')
                        .empty()
                        .append(str)

                } else {
                    new AjaxChain()
                        .setUrl('/train/team/person/list')
                        .setData({ teamId: res.id })
                        .then(data => {

                            // 初始化固定长度10的数组，全部填充null
                            var temp = Array.from({ length: 12 }, () => null);

                            // 遍历原始数组
                            $.each(data, function (_, item) {
                                temp[item.seqNo] = item;
                            });


                            var str = temp.reduce((x, y, i) => {

                                if (y) {

                                    $('#person-' + y.personId).addClass('active')
                                    return x + `<div class="bound-item">
                                                        <div class="bound-item-seq">${i}</div>
                                                        <i class="layui-icon layui-icon-disabled" title="临时禁用此位置" onclick=disabledPerson(this,${i})></i>
                                                        <div class="person-item" id="bound-item-${y.personId}">
                                                            <div class="person-item1">
                                                                <i class="layui-icon layui-icon-close" onclick=removePerson("${y.personId}")></i>
                                                                <img src="${y.photoPath ? ('/images/' + y.photoPath) : '../static/img/photo.png'}"><span>${y.personName}</span>
                                                            </div>
                                                        </div>
                                                    </div>`
                                } else {
                                    return x + `<div class="bound-item">
                                                    <div class="bound-item-seq">${i}</div>
                                                        <i class="layui-icon layui-icon-disabled" title="临时禁用此位置" onclick=disabledPerson(this,${i})></i>
                                                    <div class="person-item">
                                                    </div>
                                                </div>`
                                }

                            }, '')



                            $('#bound-list .bound-con')
                                .empty()
                                .append(str)

                        })
                        .catch(err => {
                            console.error('请求异常:', err);
                        })
                        .send();

                }



            })


        }

    });

}

var disabledList = [];// 禁用数组


//临时禁用
function disabledPerson(t, i) {

    $(t).toggleClass('active')

    if (disabledList.includes(i)) {

        disabledList = disabledList.filter(function (value) {
            return value !== i;
        });

    } else {
        disabledList.push(i)
    }

}

function removePerson(id) {


    $('#bound-item-' + id).empty();
    $('#bound-item-' + id).removeAttr("id");
    $('#person-' + id).removeClass('active')

}



// 人员选中和取消
function choosePerson(res, t) {

    var id = res.id

    if ($(t).attr('class').indexOf('active') > 0) {//如果点击前为选中状态,则取消选中,并将当前index赋予变量

        $('#bound-item-' + id).empty()
        $('#bound-item-' + id).removeAttr("id");


    } else {//如果是未选中状态,则选中,并在右侧最前方空格补位
        

        if (findFirstEmptyBoundItemIndex()>-1) {
            $('.bound-item').eq(findFirstEmptyBoundItemIndex()).find('.person-item').attr('id', ('bound-item-' + id));

            $('#bound-item-' + id)
                .empty()
                .append(`<div class="person-item1">
                            <i class="layui-icon layui-icon-close" onclick=removePerson("${res.id}")></i>
                            <img src="${res.photoPath ? ('/images/' + res.photoPath) : '../static/img/photo.png'}"><span>${res.name}</span>
                    </div>`)

        } else {
            layer.msg('该训练组位置已经满员，请释放空位后重试', { offset: ['0px', '40%'] })
            return false

        }

    }
    $(t).toggleClass('active')




}

function findFirstEmptyBoundItemIndex() {
    let targetIndex = -1;
    $('.bound-item').each(function (index) {
        // 检查当前元素是否有子元素（不包含文本节点）
        if (($(this).find('.person-item').children().length === 0) && (!disabledList.includes(index))) {
            targetIndex = index; // 记录下标
            return false;        // 终止遍历
        }
    });
    return targetIndex;
}
